package cn.sxt.userscenter.common.util;

import java.util.Date;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component("springEmailUtil")
public class SpringEmailUtil {
	@Resource
	private JavaMailSender javaMailSender ; 
	@Resource
	private SimpleMailMessage simpleMailMessage ;
	/*to: 收件人
	 *subject: 主题
	 *text:正文
	 * */
	//fasong发送第一封邮件
	public boolean sendEmail(String to,String subject,String text){
		try {
			//完善信的内容
			this.simpleMailMessage.setTo(to);
			this.simpleMailMessage.setSubject(subject);
			this.simpleMailMessage.setText(text);
			this.simpleMailMessage.setSentDate(new Date());
			//发信
			this.javaMailSender.send(simpleMailMessage);
			return true;
		} catch (MailException e) {
			ConstatFinalUtil.LOGGER.info("发送邮件失败，收件人{},内容{},主题{}：",to,subject,text,e);
			
		}
		return false;
	}
	//fasong dierfengyoujian发送第二封邮件，带链接
	public boolean sendEmailHtml(String to,String subject,String text){
		try {
			//完善信的内容
			MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
			MimeMessageHelper mailMessage = new MimeMessageHelper(mimeMessage,"UTF-8");
			
			mailMessage.setFrom(this.simpleMailMessage.getFrom());
			mailMessage.setTo(to);
			mailMessage.setSubject(subject);
			
			mailMessage.setText(text, true);//di第二个参数表示是否时html
			mailMessage.setSentDate(new Date());
			
			
			//发信
			this.javaMailSender.send(mimeMessage);
			return true;
		} catch (Exception e) {
			ConstatFinalUtil.LOGGER.info("发送邮件失败，收件人{},内容{},主题{}：",to,subject,text,e);
			
		}
		return false;
	}
}	

